package com.spica.spicaschool.ui.consult

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.drakeet.multitype.MultiTypeAdapter
import com.fondesa.recyclerviewdivider.dividerBuilder
import com.spica.spicaschool.base.ILoadMoreAdapter
import com.spica.spicaschool.base.LoadMoreAdapterWrapper
import com.spica.spicaschool.bean.PageEntity
import com.spica.spicaschool.bean.diary.Diary
import com.spica.spicaschool.utils.SpUtils
import com.spica.spicaschool.utils.TOKEN_SIGN
import com.spica.spicaschool.utils.UiUtils
import com.spica.spicaschool.view.ListLayout
import com.spica.spicaschool.viewmodel.ConsultViewModel
import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber

/**
 * 咨询
 */
@AndroidEntryPoint
class ConsultFragment : Fragment(), ILoadMoreAdapter,
    LoadMoreAdapterWrapper.OnClickRetryListener {

    private val page = PageEntity()

    private val items = mutableListOf<Diary>()

    private lateinit var adapter: MultiTypeAdapter

    private val viewModel: ConsultViewModel by viewModels()

    private var isOk = false // 是否完成View初始化

    private var isFirst = true // 是否为第一次加载

    private var isError = false

    private var isLoading = false

    private lateinit var listLayout: ListLayout


    override fun onResume() {
        super.onResume()
        initLoadData()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        listLayout = ListLayout(requireContext())
        return listLayout
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }


    private fun init() {
        initData()
    }

    private fun initData() {
        // 初始化适配器
        adapter = MultiTypeAdapter()
        // 多类型列表注册多适配器
        adapter.register(Diary::class).to(ConsultDelegate(requireActivity()))
            .withKotlinClassLinker { _, item ->
                when (item.diaryType) {
                    1 -> ConsultDelegate::class
                    else -> ConsultDelegate::class
                }
            }
        // 获取数据源
        adapter.items = items
        adapter.setHasStableIds(true) // 做diff
        listLayout.recyclerView.adapter = LoadMoreAdapterWrapper(
            requireContext(),
            adapter, this,
            this
        )

        //设置分割线
        requireContext()
            .dividerBuilder()
            .size(8, TypedValue.COMPLEX_UNIT_DIP)
            .asSpace()
            .showLastDivider()
            .showFirstDivider()
            .build()
            .addTo(listLayout.recyclerView)


        listLayout.swipeRefreshLayout.setOnRefreshListener {
            onLoadData(isRefresh = true)
        }
        isOk = true
    }


    @SuppressLint("NotifyDataSetChanged")
    private fun initLoadData() {
        if (isOk && isFirst) {
            viewModel.fetchDiaryList(
                onError = {
                    isError = true
                    Timber.e("请求过程发生错误：$it")
                },
                onComplete = {
                    isLoading = false
                    Timber.e("请求结束")
                },
                onStart = {
                    isLoading = false
                    isLoading = true
                    Timber.e("请求开始")
                },
                token = SpUtils.getSpValue(
                    context = requireContext(),
                    key = TOKEN_SIGN,
                    defaultVal = ""
                )
            )
            //初始化数据监听
            viewModel.consultsLiveData.observe(this) {
                page.nextPage = it.pageInfo.nextPage
                items.addAll(it.data)
                UiUtils.doMainThreadle({
                    listLayout.swipeRefreshLayout.isRefreshing = false
                })
                adapter.notifyDataSetChanged()
            }
            // 加载数据时判断是否完成view的初始化，以及是不是第一次加载此数据
            onLoadData(true)
            isFirst = false // 加载第一次数据后改变状态，后续不再重复加载
        }
    }

    /**
     * 加载数据
     * isRefresh：是否刷新
     **/
    @SuppressLint("NotifyDataSetChanged")
    private fun onLoadData(isRefresh: Boolean) {
        if (isRefresh) {
            isError = false
            items.clear()
            page.currentPage = 1
        }
        viewModel.pageChanged(PageEntity(currentPage = page.currentPage++))
    }

    // 加载更多
    private fun onLoadMore() {
        if (!page.nextPage) return else
            onLoadData(false)
    }


    override fun hasMoreResults(): Boolean {
        return page.nextPage
    }

    override fun hasError(): Boolean {
        return isError
    }

    override fun isLoading(): Boolean {
        if (!isLoading) {
            listLayout.swipeRefreshLayout.isRefreshing = false
        }
        return isLoading
    }

    //点击加载更多
    override fun onClickRetry() {
        Timber.e("加载更多...")
        onLoadMore()
    }
}